package window;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * source map 生成watermark 多分区的watermark
 * 只有所有分区都满足触发条件 window才会被触发
 */
public class EventTimeTumblingWindowAllDemo2 {

    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);
        // map
        SingleOutputStreamOperator<Tuple2<Long, Integer>> tupleDataStream = lines.map(new MapFunction<String, Tuple2<Long, Integer>>() {
            @Override
            public Tuple2<Long, Integer> map(String s) throws Exception {
                String[] fields = s.split(",");
                return Tuple2.of(Long.parseLong(fields[0]), Integer.parseInt(fields[1]));
            }
        });

        // 生成waterMark
        SingleOutputStreamOperator<Tuple2<Long, Integer>> tpWithWaterMark = tupleDataStream.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple2<Long, Integer>>(Time.seconds(0)) {
            @Override
            public long extractTimestamp(Tuple2<Long, Integer> longIntegerTuple2) {
                return longIntegerTuple2.f0;
            }
        });

        SingleOutputStreamOperator<Integer> nums = tpWithWaterMark.map(f -> f.f1);
        // 划分窗口
        AllWindowedStream<Integer, TimeWindow> window = nums.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)));
        // 聚合
        SingleOutputStreamOperator<Integer> summed = window.sum(0);

        summed.print();

        env.execute();
    }
}
